package com.itheima.app.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.itheima.domain.db.User;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.Map;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取token
        String token = request.getHeader("Authorization");

        //1.判断token是否为空，如果为空，返回401状态
        if(StringUtils.isEmpty(token)){
            response.setStatus(401);
            return false;
        }

        //2.判断token是否在有效期，如果失效，返回401
        Boolean hasKey=stringRedisTemplate.hasKey(ConstantUtil.USER_TOKEN + token);
        if(!hasKey){
            response.setStatus(401);
            return false;
        }


        try{//3.解析token
            Map map = JwtUtil.parseToken(token);
            User user = BeanUtil.mapToBean(map, User.class, true);
            //成功
            //查询redis有没有被最高级封号
           if (stringRedisTemplate.hasKey(user.getId()+"loginState")){
               //有 说明封了
               response.setStatus(403);
               return false;
           }

            // 1).执行token续期
            stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token, "1", Duration.ofDays(30));
            // 2).将user放入threadlocal
            UserHolder.set(user);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            //失败，返回401
            response.setStatus(401);
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
